package handler

import (
	"encoding/json"
	"lang-manager/cache"
	"lang-manager/model"
	"lang-manager/pkg"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"mas":  "不能为空",
			"code": 500,
		})
		return
	}

	user := model.User{
		Username: username,
		Password: password,
	}

	err := model.DB.Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "添加失败",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "添加成功",
		"code": 200,
	})

}

func Login(c *gin.Context) {
	username := c.PostForm("username")

	redis_is_key := "login_err" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_is_key).Int()
	if errCount > 3 {
		c.JSON(200, gin.H{
			"mas":  "密码错误3次，禁止登录",
			"code": 500,
		})
		return
	}

	var user model.User
	err := model.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "用户查询失败",
			"code": 500,
		})
		return
	}

	if user.Password != pkg.MD5(user.Password) {
		cache.Rdb.Incr(cache.Ctx, redis_is_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_is_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"mas":  "密码错误3次，封禁2小时",
				"code": 500,
			})
			return
		}
		c.JSON(200, gin.H{
			"mas":  "密码错误",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "密码正确",
		"code": 200,
	})
	return

}

func Del(c *gin.Context) {
	id := c.PostForm("id")
	err := model.DB.Where("id=?", id).Delete(&model.User{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "删除失败",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "删除成功",
		"code": 200,
	})
	return
}

func List(c *gin.Context) {

	var article []model.User
	//设置redis的key
	redis_list_ley := "list_article"
	resulit, _ := cache.Rdb.Get(cache.Ctx, redis_list_ley).Result()
	if resulit == "" {
		//从mysql数据
		model.DB.Debug().Find(&article)
		//设置到缓存redis
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_list_ley, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(resulit), &article)
	}

	c.JSON(200, gin.H{
		"message": "成功",
		"code":    200,
		"data":    article,
	})
	return
}
